package sk.mka.phd.googleagent.query;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.json.JSONObject;

/**
 *
 * @author bracek
 * @date Aug 2, 2010
 * @read http://www.michael.wiedau.com/articles/google-ajax-api-mit-java/
 */
public class AjaxGoogleQueryWiedau extends AbstractGoogleQuery implements IGoogleQuery {
    public static final String REFERER = "http://www.yahoo.com";

    private static String APIKEY = "ABQIAAAAwrDY5_HxfM6jnkoTzx8RIBR0TRJkBGvJ6nYVGkP80NshstFSdBQybbQFjLiQn5AxItNj5XROWUPLjg";
//    private static String ENDPOINTURL = "http://www.google.com/uds/GwebSearch?"
//            + "callback=GwebSearch.Raw"
//            + "Completion&amp;amp;context=0&amp;amp;lstkp=0&amp;amp;rsz=large&amp;amp;hl=en&amp;amp;"
//            + "sig=8656f49c146c5220e273d16b4b6978b2";
    private static String ENDPOINTURL = "http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0";
    private static final Logger log = Logger.getLogger(AjaxGoogleQueryWiedau.class);

    @Override
    public String makeQuery(String searchstring) {
        String results = null;

        InputStream inputStream = null;
        StringBuilder output = new StringBuilder();
        String endpoint = null;
        searchstring = searchstring.replace(" ", "+");

        try {
            endpoint = ENDPOINTURL + "&q=" + searchstring + "&key=" + APIKEY + "&amp&v=1.0";
            URL url = new URL(endpoint);
            URLConnection uc = url.openConnection();
            uc.addRequestProperty("Referer", REFERER);
            uc.setRequestProperty("User-Agent", REQUEST_VALUE);
            HttpURLConnection connection = (HttpURLConnection) uc;
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.connect();
            String line;
            inputStream = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = rd.readLine()) != null) {
                output.append(line);
            }
            String response = output.toString();
            JSONObject json = new JSONObject(response);
            results = json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount");
            inputStream.close();

        } catch (Exception e) {
            log.error(e + searchstring);
        }
        return results;
    }

    public List<GoogleResult> search(String searchstring) {

        List<GoogleResult> results = new ArrayList<GoogleResult>();
        InputStream inputStream = null;
        StringBuilder output = new StringBuilder();
        String endpoint = null;
        searchstring = searchstring.replace(" ", "+");

        try {
            endpoint = ENDPOINTURL + "&q=" + searchstring + "&key=" + APIKEY + "&amp&v=1.0";

            URL url = new URL(endpoint);
            URLConnection uc = url.openConnection();
            HttpURLConnection connection = (HttpURLConnection) uc;
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.connect();
            String line;
            inputStream = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = rd.readLine()) != null) {
                output.append(line);
            }
            inputStream.close();

            return processResult(output.toString());
        } catch (Exception e) {
            System.err.println("Something went wrong...");
        }
        return results;

    }
}
